package com.yellowframework.cloud.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Administrator
 * @version 1.0
 * @create 2018-06-17 20:45
 **/
@Configuration
public class RabbitmqConfig {

    // 交换机的名称
    public static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";

    // 队列名称
    public static final String QUEUE_INFORM_LOG = "queue_inform_log";

    // ROUTINGKEY规则
    public static final String ROUTINGKEY_LOG = "inform.#.log.#";

    // ROUTINGKEY-操作日志
    public static final String ROUTINGKEY_OPERATE_LOG = "inform.operate.log";

    // ROUTINGKEY-详细日志
    public static final String ROUTINGKEY_DETAIL_LOG = "inform.detail.log";

    /**
     * 使用JSON序列化机制，进行消息转换
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }

    /**
     * 主题模式交换机
     *
     * @return the exchange
     */
    @Bean(EXCHANGE_TOPICS_INFORM)
    public Exchange exchangeTopicsInform() {
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_INFORM).durable(true).build();
    }

    /**
     * 日志队列
     */
    @Bean(QUEUE_INFORM_LOG)
    public Queue queueLog() {
        Queue queue = new Queue(QUEUE_INFORM_LOG);
        return queue;
    }

    /**
     * 绑定日志队列到交换机
     */
    @Bean
    public Binding bindingQueueInformLog(@Qualifier(QUEUE_INFORM_LOG) Queue queue, @Qualifier(EXCHANGE_TOPICS_INFORM) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTINGKEY_LOG).noargs();
    }

}
